<!-- eslint-disable vue/attribute-hyphenation -->
<template>
    <div>
        <s-table ref="table" :search-params="searchParams" :columns="columnsAction" :async-fc="page">
            <template #tableHeader>
                <t-button v-has-perms="['system:user:manager']" @click="insert">新增信息</t-button>
            </template>
        </s-table>
        <t-dialog v-model:visible="modalOpen" header="用户管理" width="50%" @confirm="onModalSubmit">
            <t-form ref="submitFormRef" :rules="rules" :data="submitForm" labelAlign="top">
                <t-row style="width: 100%" :gutter="[16, 24]">
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.username')" name="username">
                            <t-input
                                v-model="submitForm.username"
                                :placeholder="t('pages.sysUser.usernamePlaceholder')"
                            />
                        </t-form-item>
                    </t-col>

                    <t-col v-if="!submitForm.id" :span="6">
                        <t-form-item :label="t('pages.sysUser.password')" name="password">
                            <t-input
                                v-model="submitForm.password"
                                type="password"
                                :placeholder="t('pages.sysUser.passwordPlaceholder')"
                            />
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.sex')" name="sex">
                            <t-select
                                v-model="submitForm.sex"
                                :options="sexOptions"
                                :placeholder="t('pages.sysUser.sexPlaceholder')"
                            />
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.nickname')" name="nickname">
                            <t-input
                                v-model="submitForm.nickname"
                                :placeholder="t('pages.sysUser.nicknamePlaceholder')"
                            />
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.phone')" name="phone">
                            <t-input v-model="submitForm.phone" :placeholder="t('pages.sysUser.phonePlaceholder')" />
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.email')" name="email">
                            <t-input v-model="submitForm.email" :placeholder="t('pages.sysUser.emailPlaceholder')" />
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.role')" name="role">
                            <t-select
                                v-model="submitForm.role"
                                multiple
                                :options="roleOptions"
                                :placeholder="t('pages.sysUser.rolePlaceholder')"
                            />
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.avatar')" name="avatar">
                            <s-upload
                                v-model:value="submitForm.avatar"
                                value-type="data"
                                :type="draggable"
                                :limit="1"
                                :tip="t(`pages.sysUser.avatarPlaceholder`)"
                            />
                        </t-form-item>
                    </t-col>
                    <t-col :span="6">
                        <t-form-item :label="t('pages.sysUser.remarks')" name="remarks">
                            <t-textarea
                                v-model="submitForm.remarks"
                                :placeholder="t('pages.sysUser.remarksPlaceholder')"
                            />
                        </t-form-item>
                    </t-col>
                </t-row>
            </t-form>
        </t-dialog>
    </div>
</template>
<script setup lang="ts">
/** ***                                          引用部分开始                                          */
import type { FormInstanceFunctions } from 'tdesign-vue-next';
import { DialogPlugin, Link, MessagePlugin, Space } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';

import { getOptions } from '@/api/sysRole';
import { deleteById, insertApi, page, updateApi } from '@/api/sysUser';
import STable from '@/components/s-table/index.vue';
import SUpload from '@/components/s-upload/index.vue';
import { t } from '@/locales';

import { columns, rules, searchParams, sexOptions } from './props';
/** ***                                          引用部分结束                                          */

/** ***                                          属性定义部分开始                                          */
const submitForm = ref({});
const modalOpen = ref(false);
const submitFormRef = ref<FormInstanceFunctions>(null);
const table = ref<STableInstanceFunction>(null);
const roleOptions = ref([]);
/** ***                                          属性定义部分结束                                          */

const columnsAction = columns.concat([
    {
        align: 'left',
        fixed: 'right',
        colKey: 'op',
        title: t('components.commonTable.operation'),
        cell: (h, { row }) =>
            h(Space, {}, [
                h(
                    Link,
                    {
                        theme: 'primary',
                        onClick: () => {
                            // 为了下拉回显，赋值由[{ label:'',value:''}] => ['','']
                            row.role = row.roles.map((i) => i.value);
                            console.log(row);
                            console.log(row.roles);
                            submitForm.value = row;
                            modalOpen.value = true;
                        },
                    },
                    '修改',
                ),
                h(
                    Link,
                    {
                        theme: 'danger',
                        onClick: () => {
                            const confirmDialog = DialogPlugin.confirm({
                                header: `提示`,
                                body: `删除后，标记为${row.id}的所有信息将被清空，且无法恢复`,
                                confirmBtn: {
                                    content: '提交',
                                    theme: 'primary',
                                    loading: false,
                                },
                                theme: 'warning',
                                onConfirm: async () => {
                                    confirmDialog.update({ confirmBtn: { content: '提交中', loading: true } });
                                    await deleteById(row.id);
                                    MessagePlugin.success('删除成功！');
                                    table.value.onSearch();
                                    confirmDialog.update({ confirmBtn: { content: '提交', loading: false } });
                                    confirmDialog.hide();
                                },
                            });
                        },
                    },
                    '删除',
                ),
            ]),
    },
]);

/** ***                                          页面方法开始                                          */
const insert = () => {
    modalOpen.value = true;
    submitForm.value = {
        sex: 2,
    };
};

/**
 * 提交表单
 */
const onModalSubmit = async () => {
    const valid = await submitFormRef.value.validate();
    submitForm.value = {
        ...submitForm.value,
        roles: submitForm.value.role.map((i) => ({ value: i })),
    };
    console.log('提交值', submitForm.value);
    if (valid === true) {
        if (submitForm.value.id) {
            await updateApi(submitForm.value);
        } else {
            await insertApi(submitForm.value);
        }
        MessagePlugin.success('操作成功！');
        modalOpen.value = false;
        table.value.onSearch();
    }
};

onMounted(async () => {
    const data = await getOptions();
    roleOptions.value = data;
});
/** ***                                          页面方法结束                                          */
</script>
